<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>12 发布订阅1</title>
</head>

<body>
  <button class="btn1">添加订阅</button>
  <button class="btn2">取消订阅fn1 和 fn3</button>
  <button class="btn3">通知执行</button>

  <script>
    const btn1 = document.querySelector(".btn1"),
      btn2 = document.querySelector(".btn2"),
      btn3 = document.querySelector(".btn3");

    const sub = (() => {
      // 创建事件池
      let pond = [];
      const on = (func) => {
        for (let i = 0; i < pond.length; i++) {
          if (pond[i] === func) return;
        }
        pond.push(func);
      }
      const off = (func) => {
        pond = pond.filter(item => item !== func);
      }
      const emit = (...params) => {
        pond.forEach(item => item(...params));
      }

      return { on, off, emit }
    })();

    let fn1 = (x, y) => console.log('fn1', x, y);
    let fn2 = () => {
      console.log('fn2')
    };
    let fn3 = () => console.log('fn3');
    let fn4 = () => console.log('fn4');
    let fn5 = (x, y) => console.log('fn5', x, y);

    btn1.addEventListener("click", function () {
      sub.on(fn1);
      sub.on(fn2);
      sub.on(fn3);
      sub.on(fn4);
      sub.on(fn5);
    })
    btn2.addEventListener("click", function () {
      sub.off(fn1);
      sub.off(fn3);
    })
    btn3.addEventListener("click", function () {
      sub.emit(10, 20);
    })
  </script>
</body>

</html>